using Sage.WindowsProcess.Configuration;
using Sage.WindowsProcess.Events;
using Sage.WindowsProcess.Models;
using System.Runtime.Versioning;

namespace Sage.WindowsProcess.Services
{
    /// <summary>
    /// 管理外部进程的服务
    /// </summary>
    public class ProcessManagerService : IProcessManagerService
    {
        private readonly Dictionary<string, ExternalProcessManager> _managers = [];
        private readonly Dictionary<string, ProcessConfig> _configs = [];
        private readonly Dictionary<string, ProcessEventHandlers> _eventHandlers = [];
        private readonly Lock _lock = new();
        private bool _disposed;

        /// <summary>
        /// 初始化进程管理服务
        /// </summary>
        /// <param name="configs">要管理的进程配置列表</param>
        [SupportedOSPlatform("windows")]
        public ProcessManagerService(IEnumerable<ProcessConfig> configs)
        {
            ArgumentNullException.ThrowIfNull(configs);

            // 存储配置
            foreach (var config in configs)
            {
                if (string.IsNullOrEmpty(config.Key))
                    throw new ArgumentException("进程配置必须指定Key", nameof(configs));

                if (string.IsNullOrEmpty(config.ExecutablePath))
                    throw new ArgumentException($"进程配置 {config.Key} 必须指定ExecutablePath", nameof(configs));

                _configs[config.Key] = config;
            }

            // 确保程序退出时清理资源
            AppDomain.CurrentDomain.ProcessExit += (s, e) => Dispose();
        }

        // 实现服务级事件
        /// <inheritdoc />
        public event EventHandler<ProcessServiceOutputEventArgs>? ProcessOutput;

        /// <inheritdoc />
        public event EventHandler<ProcessServiceOutputEventArgs>? ProcessError;

        /// <inheritdoc />
        public event EventHandler<ProcessServiceStartedEventArgs>? ProcessStarted;

        /// <inheritdoc />
        public event EventHandler<ProcessServiceExitedEventArgs>? ProcessExited;

        /// <inheritdoc />
        public event EventHandler<ProcessServiceErrorEventArgs>? ProcessServiceError;

        /// <inheritdoc />
        public event EventHandler<ProcessServiceStatusEventArgs>? ProcessStatusUpdated;

        #region 事件触发方法
        /// <summary>
        /// 触发进程输出事件
        /// </summary>
        [SupportedOSPlatform("windows")]
        protected virtual void OnProcessOutput(string key, string data)
        {
            ProcessOutput?.Invoke(this, new ProcessServiceOutputEventArgs(key, data));
        }

        /// <summary>
        /// 触发进程错误输出事件
        /// </summary>
        [SupportedOSPlatform("windows")]
        protected virtual void OnProcessError(string key, string data)
        {
            ProcessError?.Invoke(this, new ProcessServiceOutputEventArgs(key, data));
        }

        /// <summary>
        /// 触发进程启动事件
        /// </summary>
        [SupportedOSPlatform("windows")]
        protected virtual void OnProcessStarted(string key, int processId)
        {
            ProcessStarted?.Invoke(this, new ProcessServiceStartedEventArgs(key, processId));
        }

        /// <summary>
        /// 触发进程退出事件
        /// </summary>
        [SupportedOSPlatform("windows")]
        protected virtual void OnProcessExited(string key, int exitCode)
        {
            ProcessExited?.Invoke(this, new ProcessServiceExitedEventArgs(key, exitCode));
        }

        /// <summary>
        /// 触发服务错误事件
        /// </summary>
        [SupportedOSPlatform("windows")]
        protected virtual void OnProcessServiceError(string key, string errorMessage, Exception? exception = null)
        {
            ProcessServiceError?.Invoke(this, new ProcessServiceErrorEventArgs(key, errorMessage, exception));
        }

        /// <summary>
        /// 触发进程状态更新事件
        /// </summary>
        [SupportedOSPlatform("windows")]
        protected virtual void OnProcessStatusUpdated(string key, double cpuUsage, long memoryUsage, TimeSpan runningTime, int threadCount)
        {
            ProcessStatusUpdated?.Invoke(this, new ProcessServiceStatusEventArgs(key, cpuUsage, memoryUsage, runningTime, threadCount));
        }
        #endregion

        /// <inheritdoc />
        public IEnumerable<string> GetAllKeys() => _configs.Keys;

        /// <inheritdoc />
        public ProcessConfig? GetConfig(string key)
        {
            return _configs.TryGetValue(key, out var config) ? config : null;
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public bool AddConfig(ProcessConfig config)
        {
            ArgumentNullException.ThrowIfNull(config);
            if (string.IsNullOrEmpty(config.Key))
                throw new ArgumentException("进程配置必须指定Key", nameof(config));
            if (string.IsNullOrEmpty(config.ExecutablePath))
                throw new ArgumentException($"进程配置 {config.Key} 必须指定ExecutablePath", nameof(config));
            lock (_lock)
            {
                // 检查是否已存在同名配置
                if (_configs.ContainsKey(config.Key))
                {
                    // 如果进程正在运行，不允许替换配置
                    if (_managers.TryGetValue(config.Key, out var manager) && manager.IsRunning)
                    {
                        OnProcessServiceError(config.Key, $"无法添加配置：进程 {config.Key} 正在运行");
                        return false;
                    }
                }
                // 添加或更新配置
                _configs[config.Key] = config;
                return true;
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public bool AddConfig(IEnumerable<ProcessConfig> configs)
        {
            ArgumentNullException.ThrowIfNull(configs);
            bool allSuccess = true;
            foreach (var config in configs)
            {
                if (!AddConfig(config))
                {
                    allSuccess = false;
                }
            }

            return allSuccess;
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public async Task<bool> RemoveConfigAsync(string key, bool stopRunning = true)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));

            lock (_lock)
            {
                // 检查配置是否存在
                if (!_configs.ContainsKey(key))
                {
                    // 配置不存在，视为已移除
                    return true;
                }
            }

            try
            {
                // 如果需要停止进程且进程正在运行
                if (stopRunning && IsRunning(key))
                {
                    // 尝试停止进程
                    bool stopped = await StopAsync(key);
                    if (!stopped)
                    {
                        OnProcessServiceError(key, $"无法停止进程 {key}，移除失败");
                        return false;
                    }
                }

                lock (_lock)
                {
                    // 移除进程管理器
                    if (_managers.TryGetValue(key, out var manager))
                    {
                        // 取消事件订阅
                        if (_eventHandlers.TryGetValue(key, out var handlers))
                        {
                            handlers.Unsubscribe();
                            _eventHandlers.Remove(key);
                        }

                        // 处置管理器
                        manager.Dispose();
                        _managers.Remove(key);
                    }

                    // 移除配置
                    _configs.Remove(key);

                    return true;
                }
            }
            catch (Exception ex)
            {
                OnProcessServiceError(key, $"移除进程 {key} 时发生错误: {ex.Message}", ex);
                return false;
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        [Obsolete("方法将被弃用，请改用AddConfig", false)]
        public bool AddProcess(ProcessConfig config)
        {
            ArgumentNullException.ThrowIfNull(config);

            if (string.IsNullOrEmpty(config.Key))
                throw new ArgumentException("进程配置必须指定Key", nameof(config));

            if (string.IsNullOrEmpty(config.ExecutablePath))
                throw new ArgumentException($"进程配置 {config.Key} 必须指定ExecutablePath", nameof(config));

            lock (_lock)
            {
                // 检查是否已存在同名配置
                if (_configs.ContainsKey(config.Key))
                {
                    // 如果进程正在运行，不允许替换配置
                    if (_managers.TryGetValue(config.Key, out var manager) && manager.IsRunning)
                    {
                        OnProcessServiceError(config.Key, $"无法添加配置：进程 {config.Key} 正在运行");
                        return false;
                    }
                }

                // 添加或更新配置
                _configs[config.Key] = config;
                return true;
            }
        }


        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        [Obsolete("方法将被弃用，请改用RemoveConfigAsync", false)]
        public async Task<bool> RemoveProcessAsync(string key, bool stopRunning = true)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));

            lock (_lock)
            {
                // 检查配置是否存在
                if (!_configs.ContainsKey(key))
                {
                    // 配置不存在，视为已移除
                    return true;
                }
            }

            try
            {
                // 如果需要停止进程且进程正在运行
                if (stopRunning && IsRunning(key))
                {
                    // 尝试停止进程
                    bool stopped = await StopAsync(key);
                    if (!stopped)
                    {
                        OnProcessServiceError(key, $"无法停止进程 {key}，移除失败");
                        return false;
                    }
                }

                lock (_lock)
                {
                    // 移除进程管理器
                    if (_managers.TryGetValue(key, out var manager))
                    {
                        // 取消事件订阅
                        if (_eventHandlers.TryGetValue(key, out var handlers))
                        {
                            handlers.Unsubscribe();
                            _eventHandlers.Remove(key);
                        }

                        // 处置管理器
                        manager.Dispose();
                        _managers.Remove(key);
                    }

                    // 移除配置
                    _configs.Remove(key);

                    return true;
                }
            }
            catch (Exception ex)
            {
                OnProcessServiceError(key, $"移除进程 {key} 时发生错误: {ex.Message}", ex);
                return false;
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        [Obsolete("方法将被弃用，请改用AddConfigs", false)]
        public bool AddProcesses(IEnumerable<ProcessConfig> configs)
        {
            ArgumentNullException.ThrowIfNull(configs);

            bool allSuccess = true;
            foreach (var config in configs)
            {
                if (!AddProcess(config))
                {
                    allSuccess = false;
                }
            }

            return allSuccess;
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public async Task StartAllAsync(int timeout = 30000)
        {
            List<Exception> exceptions = [];

            foreach (var key in _configs.Keys)
            {
                try
                {
                    await StartAsync(key, timeout);
                }
                catch (Exception ex)
                {
                    exceptions.Add(new Exception($"启动进程 {key} 失败: {ex.Message}", ex));
                }
            }

            if (exceptions.Count > 0)
            {
                throw new AggregateException("启动部分进程失败", exceptions);
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public async Task<bool> StartAsync(string key, int timeout = 30000)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));

            // 获取配置
            if (!_configs.TryGetValue(key, out var config))
            {
                throw new KeyNotFoundException($"未找到进程配置: {key}");
            }

            // 检查进程是否已在运行
            lock (_lock)
            {
                if (_managers.TryGetValue(key, out var existingManager) && existingManager.IsRunning)
                {
                    return true;
                }
            }

            // 确保可执行文件存在
            if (!File.Exists(config.ExecutablePath))
            {
                throw new FileNotFoundException($"找不到可执行文件: {config.ExecutablePath}");
            }

            try
            {
                // 创建进程管理器
                var manager = new ExternalProcessManager(
                    Path.GetFileNameWithoutExtension(config.ExecutablePath),
                    config.ExecutablePath)
                {
                    Arguments = config.Arguments,
                    WorkingDirectory = config.WorkingDirectory ?? Path.GetDirectoryName(config.ExecutablePath),
                    AutoRestart = config.AutoRestart,
                    RestartDelayMs = config.RestartDelayMs,
                    MaxRestartAttempts = config.MaxRestartAttempts,
                    MonitoringEnabled = config.EnableMonitoring,
                    MonitoringIntervalMs = config.MonitoringIntervalMs,
                    CreateNoWindow = config.CreateNoWindow,
                    RedirectOutput = config.RedirectOutput,
                    ProcessPriority = config.ProcessPriority
                };

                // 创建并订阅事件处理器
                var handlers = new ProcessEventHandlers(this, key, manager);

                // 启动进程，传递超时参数
                bool started = await manager.StartProcessAsync(timeout);

                lock (_lock)
                {
                    if (started)
                    {
                        // 如果存在旧的管理器实例，先处置它
                        if (_managers.TryGetValue(key, out var oldManager))
                        {
                            // 取消旧的事件订阅
                            if (_eventHandlers.TryGetValue(key, out var oldHandlers))
                            {
                                oldHandlers.Unsubscribe();
                                _eventHandlers.Remove(key);
                            }

                            oldManager.Dispose();
                        }

                        // 存储新的管理器和事件处理器
                        _managers[key] = manager;
                        _eventHandlers[key] = handlers;
                        return true;
                    }
                    else
                    {
                        // 如果启动失败，取消事件订阅并清理
                        handlers.Unsubscribe();
                        manager.Dispose();
                        OnProcessServiceError(key, $"无法启动进程 {key}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                OnProcessServiceError(key, $"启动进程时发生错误: {ex.Message}", ex);
                throw; // 重新抛出异常以便调用者处理
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public async Task StopAllAsync(int timeout = 5000)
        {
            List<Exception> exceptions = [];

            // 复制键集合以避免在迭代过程中修改集合
            var keys = _managers.Keys.ToList();

            foreach (var key in keys)
            {
                try
                {
                    await StopAsync(key, timeout);
                }
                catch (Exception ex)
                {
                    exceptions.Add(new Exception($"停止进程 {key} 失败: {ex.Message}", ex));
                }
            }

            if (exceptions.Count > 0)
            {
                throw new AggregateException("停止部分进程失败", exceptions);
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public async Task<bool> StopAsync(string key, int timeout = 5000)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));

            // 获取进程管理器
            ExternalProcessManager? manager;
            lock (_lock)
            {
                if (!_managers.TryGetValue(key, out manager))
                {
                    return true; // 如果进程不在管理中，视为已停止
                }

                if (!manager.IsRunning)
                {
                    return true;
                }
            }

            // 确保manager不为null
            if (manager == null) return true;

            try
            {
                // 停止进程，传递超时参数
                bool stopped = await manager.StopProcessAsync(timeout);

                lock (_lock)
                {
                    // 取消事件订阅
                    if (_eventHandlers.TryGetValue(key, out var handlers))
                    {
                        handlers.Unsubscribe();
                        _eventHandlers.Remove(key);
                    }

                    if (stopped)
                    {
                        return true;
                    }
                    else
                    {
                        OnProcessServiceError(key, $"无法正常停止进程，尝试强制终止");
                        manager.StopProcess(0); // 强制终止，无等待
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                OnProcessServiceError(key, $"停止进程时发生错误: {ex.Message}", ex);

                // 尝试强制终止
                try
                {
                    manager.StopProcess(0);
                }
                catch
                {
                    // 忽略强制终止时的异常
                }

                throw; // 重新抛出原始异常
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public async Task<bool> RestartAsync(string key, int startTimeout = 30000, int stopTimeout = 5000)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));

            // 先停止进程，传递停止超时参数
            await StopAsync(key, stopTimeout);

            // 然后启动进程
            // 注意：StartAsync方法目前不支持timeout参数，这里无法传递startTimeout
            // 未来可以考虑增强StartAsync方法以支持timeout参数
            return await StartAsync(key);
        }

        /// <inheritdoc />
        public bool IsRunning(string key)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));

            lock (_lock)
            {
                return _managers.TryGetValue(key, out var manager) && manager.IsRunning;
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public ProcessStatusInfo? GetStatus(string key)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));

            lock (_lock)
            {
                return _managers.TryGetValue(key, out var manager) ? manager.GetProcessStatus() : null;
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public bool SetProcessPriority(string key, System.Diagnostics.ProcessPriorityClass priority)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));

            lock (_lock)
            {
                if (_managers.TryGetValue(key, out var manager))
                {
                    try
                    {
                        // 设置进程优先级
                        manager.ProcessPriority = priority;

                        // 更新配置中的优先级设置，以便重启时保持一致
                        if (_configs.TryGetValue(key, out var config))
                        {
                            config.ProcessPriority = priority;
                        }

                        return true;
                    }
                    catch (Exception ex)
                    {
                        OnProcessServiceError(key, $"设置进程优先级失败: {ex.Message}", ex);
                        return false;
                    }
                }
                else
                {
                    OnProcessServiceError(key, $"无法设置优先级：进程 {key} 未运行");
                    return false;
                }
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public async ValueTask<bool> WriteToStandardInputAsync(string key, string input, CancellationToken cancellationToken = default)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));
            ArgumentException.ThrowIfNullOrEmpty(input, nameof(input));

            ExternalProcessManager? manager;
            lock (_lock)
            {
                if (!_managers.TryGetValue(key, out manager) || !manager.IsRunning)
                {
                    return false; // 进程不存在或未运行
                }
            }

            // 确保manager不为null
            if (manager == null) return false;

            try
            {
                // 向进程标准输入写入数据
                return await manager.WriteToStandardInputAsync(input, cancellationToken);
            }
            catch (Exception ex)
            {
                OnProcessServiceError(key, $"向进程写入标准输入失败: {ex.Message}", ex);
                return false;
            }
        }

        /// <inheritdoc />
        [SupportedOSPlatform("windows")]
        public async Task<bool> WaitForExitAsync(string key, int timeout = -1, CancellationToken cancellationToken = default)
        {
            ArgumentException.ThrowIfNullOrEmpty(key, nameof(key));

            ExternalProcessManager? manager;
            lock (_lock)
            {
                if (!_managers.TryGetValue(key, out manager) || !manager.IsRunning)
                {
                    return true; // 进程不存在或未运行，视为已退出
                }
            }

            // 确保manager不为null
            if (manager == null) return true;

            try
            {
                // 等待进程退出
                return await manager.WaitForExitAsync(timeout, cancellationToken);
            }
            catch (Exception ex)
            {
                OnProcessServiceError(key, $"等待进程退出时发生错误: {ex.Message}", ex);
                return false;
            }
        }

        /// <summary>
        /// 异步释放资源
        /// </summary>
        [SupportedOSPlatform("windows")]
        public async ValueTask DisposeAsync()
        {
            // 执行异步清理
            await DisposeAsyncCore();

            // 执行同步清理，但跳过已经异步清理的部分
            Dispose(false);

            // 抑制终结器
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 异步资源释放的核心逻辑
        /// </summary>
        [SupportedOSPlatform("windows")]
        protected virtual async ValueTask DisposeAsyncCore()
        {
            if (_disposed)
                return;

            try
            {
                // 异步停止所有进程
                try
                {
                    await StopAllAsync();
                }
                catch
                {
                    // 忽略停止过程中的异常
                }
            }
            finally
            {
                // 确保所有资源被清理
                lock (_lock)
                {
                    foreach (var entry in _managers)
                    {
                        try
                        {
                            // 取消事件订阅
                            if (_eventHandlers.TryGetValue(entry.Key, out var handlers))
                            {
                                handlers.Unsubscribe();
                            }

                            entry.Value.Dispose();
                        }
                        catch
                        {
                            // 忽略清理过程中的异常
                        }
                    }

                    _managers.Clear();
                    _eventHandlers.Clear();
                }

                _disposed = true;
            }
        }

        /// <summary>
        /// 实现 IDisposable 接口
        /// </summary>
        [SupportedOSPlatform("windows")]
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        [SupportedOSPlatform("windows")]
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                try
                {
                    // 尝试停止所有进程（使用同步方法，但更安全的调用方式）
                    try
                    {
                        StopAllAsync().GetAwaiter().GetResult();
                    }
                    catch
                    {
                        // 忽略停止过程中的异常
                    }

                    // 确保所有资源被清理
                    lock (_lock)
                    {
                        foreach (var entry in _managers)
                        {
                            try
                            {
                                // 取消事件订阅
                                if (_eventHandlers.TryGetValue(entry.Key, out var handlers))
                                {
                                    handlers.Unsubscribe();
                                }

                                entry.Value.Dispose();
                            }
                            catch
                            {
                                // 忽略清理过程中的异常
                            }
                        }

                        _managers.Clear();
                        _eventHandlers.Clear();
                    }
                }
                catch
                {
                    // 确保即使在异常情况下也能继续清理
                }
            }

            _disposed = true;
        }

        /// <summary>
        /// 析构函数
        /// </summary>
        [SupportedOSPlatform("windows")]
        ~ProcessManagerService()
        {
            Dispose(false);
        }

        /// <summary>
        /// 进程事件处理器类，用于管理事件订阅
        /// </summary>
        private class ProcessEventHandlers
        {
            private readonly ExternalProcessManager _manager;
            private readonly string _key;
            private readonly ProcessManagerService _service;
            private bool _subscribed;

            /// <summary>
            /// 初始化事件处理器并订阅事件
            /// </summary>
            [SupportedOSPlatform("windows")]
            public ProcessEventHandlers(ProcessManagerService service, string key, ExternalProcessManager manager)
            {
                _service = service;
                _key = key;
                _manager = manager;
                Subscribe();
            }

            /// <summary>
            /// 订阅进程管理器的事件
            /// </summary>
            [SupportedOSPlatform("windows")]
            public void Subscribe()
            {
                if (_subscribed) return;

                if (_manager.RedirectOutput)
                {
                    _manager.OutputReceived += OnOutputReceived;
                    _manager.ErrorReceived += OnErrorReceived;
                }

                _manager.ProcessStarted += OnProcessStarted;
                _manager.ProcessExited += OnProcessExited;
                _manager.ProcessError += OnProcessError;
                _manager.ProcessStatusUpdated += OnProcessStatusUpdated;

                _subscribed = true;
            }

            /// <summary>
            /// 取消订阅进程管理器的事件
            /// </summary>
            [SupportedOSPlatform("windows")]
            public void Unsubscribe()
            {
                if (!_subscribed) return;

                if (_manager.RedirectOutput)
                {
                    _manager.OutputReceived -= OnOutputReceived;
                    _manager.ErrorReceived -= OnErrorReceived;
                }

                _manager.ProcessStarted -= OnProcessStarted;
                _manager.ProcessExited -= OnProcessExited;
                _manager.ProcessError -= OnProcessError;
                _manager.ProcessStatusUpdated -= OnProcessStatusUpdated;

                _subscribed = false;
            }


            /// <summary>
            /// 处理进程的标准输出数据接收事件。
            /// 将收到的输出数据记录到控制台并转发到服务级事件。
            /// </summary>
            /// <param name="sender">事件源对象</param>
            /// <param name="e">包含输出数据的事件参数</param>
            [SupportedOSPlatform("windows")]
            private void OnOutputReceived(object? sender, ProcessOutputEventArgs e)
            {
                Console.WriteLine($"[{_key}] 输出: {e.Data}");
                _service.OnProcessOutput(_key, e.Data);
            }

            /// <summary>
            /// 处理进程的标准错误输出数据接收事件。
            /// 将收到的错误数据记录到控制台并转发到服务级事件。
            /// </summary>
            /// <param name="sender">事件源对象</param>
            /// <param name="e">包含错误输出数据的事件参数</param>
            [SupportedOSPlatform("windows")]
            private void OnErrorReceived(object? sender, ProcessOutputEventArgs e)
            {
                Console.WriteLine($"[{_key}] 错误: {e.Data}");
                _service.OnProcessError(_key, e.Data);
            }

            /// <summary>
            /// 处理进程启动事件。
            /// 记录进程启动信息并将事件转发到服务级事件。
            /// </summary>
            /// <param name="sender">事件源对象</param>
            /// <param name="e">包含进程信息的事件参数</param>
            [SupportedOSPlatform("windows")]
            private void OnProcessStarted(object? sender, ProcessEventArgs e)
            {
                Console.WriteLine($"[{_key}] 已启动，进程ID: {e.Process.Id}");
                _service.OnProcessStarted(_key, e.Process.Id);
            }

            /// <summary>
            /// 处理进程退出事件。
            /// 记录进程退出信息（包括退出代码）并将事件转发到服务级事件。
            /// </summary>
            /// <param name="sender">事件源对象</param>
            /// <param name="e">包含进程退出信息的事件参数</param>
            [SupportedOSPlatform("windows")]
            private void OnProcessExited(object? sender, ProcessExitedEventArgs e)
            {
                Console.WriteLine($"[{_key}] 已退出，退出代码: {e.ExitCode}");
                _service.OnProcessExited(_key, e.ExitCode);
            }

            /// <summary>
            /// 处理进程操作中发生的错误事件。
            /// 记录错误信息并将事件转发到服务级错误事件。
            /// </summary>
            /// <param name="sender">事件源对象</param>
            /// <param name="e">包含错误详情的事件参数</param>
            [SupportedOSPlatform("windows")]
            private void OnProcessError(object? sender, ProcessErrorEventArgs e)
            {
                Console.WriteLine($"[{_key}] 错误: {e.ErrorMessage}");
                _service.OnProcessServiceError(_key, e.ErrorMessage, e.Exception);
            }

            /// <summary>
            /// 处理进程状态更新事件。
            /// 将CPU使用率、内存使用量等进程状态信息转发到服务级状态更新事件。
            /// </summary>
            /// <param name="sender">事件源对象</param>
            /// <param name="e">包含进程状态信息的事件参数</param>
            [SupportedOSPlatform("windows")]
            private void OnProcessStatusUpdated(object? sender, ProcessStatusEventArgs e)
            {
                _service.OnProcessStatusUpdated(_key, e.CpuUsage, e.MemoryUsage, e.RunningTime, e.ThreadCount);
            }

        }
    }
}
